#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QtCharts/QValueAxis>
#include <QtCharts/QDateTimeAxis>
#include <QRandomGenerator>
#include <QVBoxLayout>
#include <QDateTime>
#include <QPixmap>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , timer(new QTimer(this))
    , currentTime(QDateTime::currentDateTime())
{
    ui->setupUi(this);

    // 加载图片并按比例缩放
    QPixmap pixmap(":/image.png");
    if (!pixmap.isNull()) {
        // 按比例缩放到imageLabel大小，保持宽高比
        QPixmap scaledPixmap = pixmap.scaledToWidth(width() - 10, Qt::SmoothTransformation);
        ui->imageLabel->setPixmap(scaledPixmap);
        ui->imageLabel->resize(scaledPixmap.size());
    } else {
        qDebug() << "Failed to load image: :/image.png";
    }

    // 初始化图表
    setupCharts();

    // 设置定时器，每秒更新数据
    connect(timer, &QTimer::timeout, this, &MainWindow::updateCharts);
    timer->start(1000);

    // 初始更新数据标签
    updateDataLabels();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupCharts()
{
    // 初始化压力图表
    pressureSeries = new QtCharts::QLineSeries();
    pressureChart = new QtCharts::QChart();
    pressureChart->addSeries(pressureSeries);
    pressureChart->setTitle("压力");
    pressureChart->setMargins(QMargins(20, 20, 20, 20));
    pressureChart->setBackgroundVisible(true);
    QtCharts::QDateTimeAxis *axisX = new QtCharts::QDateTimeAxis();
    axisX->setFormat("HH:mm");
    axisX->setRange(currentTime.addSecs(-60), currentTime);
    axisX->setTickCount(2); // 1分钟间隔，60秒内2个点（当前和1分钟前）
    axisX->setLabelsVisible(true);
    QtCharts::QValueAxis *axisY = new QtCharts::QValueAxis();
    axisY->setRange(0, 500);
    axisY->setTickCount(5); // 0, 125, 250, 375, 500
    axisY->setLabelFormat("%.0f");
    axisY->setLabelsVisible(true);
    pressureChart->addAxis(axisX, Qt::AlignBottom);
    pressureChart->addAxis(axisY, Qt::AlignLeft);
    pressureSeries->attachAxis(axisX);
    pressureSeries->attachAxis(axisY);
    QtCharts::QChartView *pressureChartView = new QtCharts::QChartView(pressureChart, ui->pressureChartWidget);
    pressureChartView->setRenderHint(QPainter::Antialiasing);
    pressureChartView->setMinimumSize(0, 300); // 减小高度到300
    ui->pressureChartWidget->setLayout(new QVBoxLayout());
    ui->pressureChartWidget->layout()->addWidget(pressureChartView);

    // 初始化振动图表
    vibrationSeries = new QtCharts::QLineSeries();
    vibrationChart = new QtCharts::QChart();
    vibrationChart->addSeries(vibrationSeries);
    vibrationChart->setTitle("振动");
    vibrationChart->setMargins(QMargins(20, 20, 20, 20));
    vibrationChart->setBackgroundVisible(true);
    axisX = new QtCharts::QDateTimeAxis();
    axisX->setFormat("HH:mm");
    axisX->setRange(currentTime.addSecs(-60), currentTime);
    axisX->setTickCount(2);
    axisX->setLabelsVisible(true);
    axisY = new QtCharts::QValueAxis();
    axisY->setRange(0, 100);
    axisY->setTickCount(5); // 0, 25, 50, 75, 100
    axisY->setLabelFormat("%.0f");
    axisY->setLabelsVisible(true);
    vibrationChart->addAxis(axisX, Qt::AlignBottom);
    vibrationChart->addAxis(axisY, Qt::AlignLeft);
    vibrationSeries->attachAxis(axisX);
    vibrationSeries->attachAxis(axisY);
    QtCharts::QChartView *vibrationChartView = new QtCharts::QChartView(vibrationChart, ui->vibrationChartWidget);
    vibrationChartView->setRenderHint(QPainter::Antialiasing);
    vibrationChartView->setMinimumSize(0, 300);
    ui->vibrationChartWidget->setLayout(new QVBoxLayout());
    ui->vibrationChartWidget->layout()->addWidget(vibrationChartView);

    // 初始化形变图表
    deformationSeries = new QtCharts::QLineSeries();
    deformationChart = new QtCharts::QChart();
    deformationChart->addSeries(deformationSeries);
    deformationChart->setTitle("形变");
    deformationChart->setMargins(QMargins(20, 20, 20, 20));
    deformationChart->setBackgroundVisible(true);
    axisX = new QtCharts::QDateTimeAxis();
    axisX->setFormat("HH:mm");
    axisX->setRange(currentTime.addSecs(-60), currentTime);
    axisX->setTickCount(2);
    axisX->setLabelsVisible(true);
    axisY = new QtCharts::QValueAxis();
    axisY->setRange(0, 50);
    axisY->setTickCount(5); // 0, 12.5, 25, 37.5, 50
    axisY->setLabelFormat("%.1f");
    axisY->setLabelsVisible(true);
    deformationChart->addAxis(axisX, Qt::AlignBottom);
    deformationChart->addAxis(axisY, Qt::AlignLeft);
    deformationSeries->attachAxis(axisX);
    deformationSeries->attachAxis(axisY);
    QtCharts::QChartView *deformationChartView = new QtCharts::QChartView(deformationChart, ui->deformationChartWidget);
    deformationChartView->setRenderHint(QPainter::Antialiasing);
    deformationChartView->setMinimumSize(0, 300);
    ui->deformationChartWidget->setLayout(new QVBoxLayout());
    ui->deformationChartWidget->layout()->addWidget(deformationChartView);
}

void MainWindow::updateCharts()
{
    // 更新时间
    currentTime = QDateTime::currentDateTime();

    // 生成低范围随机数据
    static double lastPressure = 100.0; // 初始值
    static double lastVibration = 20.0;
    static double lastDeformation = 10.0;
    lastPressure += QRandomGenerator::global()->bounded((qint32)-5.0, 5.0); // 小幅波动
    lastVibration += QRandomGenerator::global()->bounded((qint32)-2.0, 2.0);
    lastDeformation += QRandomGenerator::global()->bounded((qint32)-1.0, 1.0);
    // 限制范围
    lastPressure = qBound(80.0, lastPressure, 120.0); // 80-120 N
    lastVibration = qBound(15.0, lastVibration, 25.0); // 15-25 rps
    lastDeformation = qBound(8.0, lastDeformation, 12.0); // 8-12 mm

    // 更新数据
    pressureData.append(QPointF(currentTime.toMSecsSinceEpoch(), lastPressure));
    vibrationData.append(QPointF(currentTime.toMSecsSinceEpoch(), lastVibration));
    deformationData.append(QPointF(currentTime.toMSecsSinceEpoch(), lastDeformation));

    // 保持60秒数据
    qint64 timeThreshold = currentTime.addSecs(-60).toMSecsSinceEpoch();
    while (!pressureData.isEmpty() && pressureData.first().x() < timeThreshold) {
        pressureData.removeFirst();
        vibrationData.removeFirst();
        deformationData.removeFirst();
    }

    // 更新图表
    pressureSeries->replace(pressureData);
    vibrationSeries->replace(vibrationData);
    deformationSeries->replace(deformationData);

    // 更新X轴范围
    pressureChart->axisX()->setRange(currentTime.addSecs(-60), currentTime);
    vibrationChart->axisX()->setRange(currentTime.addSecs(-60), currentTime);
    deformationChart->axisX()->setRange(currentTime.addSecs(-60), currentTime);

    // 更新数据标签
    updateDataLabels();
}

void MainWindow::updateDataLabels()
{
    // 更新压力
    double pressure = pressureData.isEmpty() ? 100.0 : pressureData.last().y();
    ui->pressureValue->setText(QString("%1 N").arg(pressure, 0, 'f', 1));
    ui->pressureStatus->setText(pressure < 110 ? "正常" : "异常");

    // 更新振动1-3（使用相同振动值）
    double vibration = vibrationData.isEmpty() ? 20.0 : vibrationData.last().y();
    ui->vibration1Value->setText(QString("%1 rps").arg(vibration, 0, 'f', 1));
    ui->vibration1Status->setText(vibration < 22 ? "正常" : "异常");
    ui->vibration2Value->setText(QString("%1 rps").arg(vibration, 0, 'f', 1));
    ui->vibration2Status->setText(vibration < 22 ? "正常" : "异常");
    ui->vibration3Value->setText(QString("%1 rps").arg(vibration, 0, 'f', 1));
    ui->vibration3Status->setText(vibration < 22 ? "正常" : "异常");

    // 更新形变1-3（使用相同形变值）
    double deformation = deformationData.isEmpty() ? 10.0 : deformationData.last().y();
    ui->deformation1Value->setText(QString("%1 mm").arg(deformation, 0, 'f', 1));
    ui->deformation1Status->setText(deformation < 11 ? "正常" : "异常");
    ui->deformation2Value->setText(QString("%1 mm").arg(deformation, 0, 'f', 1));
    ui->deformation2Status->setText(deformation < 11 ? "正常" : "异常");
    ui->deformation3Value->setText(QString("%1 mm").arg(deformation, 0, 'f', 1));
    ui->deformation3Status->setText(deformation < 11 ? "正常" : "异常");
}

void MainWindow::on_searchButton_clicked()
{
    ui->comPortComboBox->addItem(QString("COM%1 USB-SER%1").arg(ui->comPortComboBox->count() + 5));
}

void MainWindow::on_connectButton_clicked()
{
    ui->connectionStatus->setText("在线");
}

void MainWindow::on_disconnectButton_clicked()
{
    ui->connectionStatus->setText("离线");
}
